package com.ruyiadmin.springboot.service.impls.system;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruyiadmin.springboot.common.core.system.entities.ActionResult;
import com.ruyiadmin.springboot.common.core.system.entities.QueryResult;
import com.ruyiadmin.springboot.common.utils.system.RuYiCodeUtil;
import com.ruyiadmin.springboot.domain.dto.system.CodeGeneratorDTO;
import com.ruyiadmin.springboot.domain.dto.system.DbSchemaInfoDTO;
import com.ruyiadmin.springboot.repository.system.ICodeGeneratorRepository;
import com.ruyiadmin.springboot.service.iservices.system.ICodeGeneratorService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * 代码生成器 服务实现类
 * </p>
 *
 * @author RuYiAdmin
 * @since 2022-08-05
 */
@Service
@RequiredArgsConstructor
public class CodeGeneratorService extends ServiceImpl<ICodeGeneratorRepository, DbSchemaInfoDTO>
        implements ICodeGeneratorService {

    private final ICodeGeneratorRepository codeGeneratorRepository;

    //region 查询库空间信息

    /**
     * 查询数据库空间信息
     *
     * @return QueryResult
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public QueryResult<DbSchemaInfoDTO> querySchemaInfo() {
        List<DbSchemaInfoDTO> list = this.codeGeneratorRepository.queryMySqlSchemaInfo();
        return QueryResult.success(list.size(), list);
    }

    //endregion

    //region 生成项目代码

    /**
     * 生成项目代码
     *
     * @param codeGenerator CodeGeneratorDTO
     * @return ActionResult
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public ActionResult codeGenerate(CodeGeneratorDTO codeGenerator) throws IOException {
        List<String> tables = Arrays.asList(codeGenerator.getTables().split(","));
        int layoutMode = codeGenerator.getLayoutMode();
        return ActionResult.success(RuYiCodeUtil.AutoGenerateCode(tables, layoutMode));
    }

    //endregion

}
